package org.springblade.modules.task;

import org.quartz.*;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.huikecloud.service.AsyncService;
import org.springblade.modules.task.entity.BladeJob;
import org.springblade.modules.task.service.IJobService;
import org.springblade.modules.task.service.impl.JobServiceImpl;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

public class JobUtil {

    public static SchedulerFactoryBean schedulerFactoryBean = SpringUtil.getBean(SchedulerFactoryBean.class);
    public static AsyncService asyncService = SpringUtil.getBean(AsyncService.class);
    public static IJobService jobService = SpringUtil.getBean(JobServiceImpl.class);


    /**
     * 添加任务
     *
     * @param bladeJob
     * @throws SchedulerException
     */
    public static boolean addJob(BladeJob bladeJob) {
        if (bladeJob == null) {
            return false;
        }
        try {
            JobDetail oldJob = schedulerFactoryBean.getScheduler().getJobDetail(JobKey.jobKey(bladeJob.getJobName(), bladeJob.getJobGroupName()));
            if (oldJob!=null){
                delJob((BladeJob) oldJob.getJobDataMap().get("BladeJob"));
            }

            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(bladeJob.getJobName(), bladeJob.getJobGroupName());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 不存在，创建一个
            if (null == trigger) {
//            Class clazz = "1".equals(job.getIsConcurrent()) ? QuartzJobFactory.class
//                    : QuartzJobFactoryDisallowConcurrentExecution.class;
                JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(bladeJob.getJobName(), bladeJob.getJobGroupName())
                        .usingJobData("data", bladeJob.getMethodParameters()).build();
                jobDetail.getJobDataMap().put("BladeJob", bladeJob);
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(bladeJob.getCronExpression());
                trigger = TriggerBuilder.newTrigger().withDescription(bladeJob.getId().toString())
                        .withIdentity(bladeJob.getJobName(), bladeJob.getJobGroupName()).withSchedule(scheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, trigger);
                return true;
            } else {
                // Trigger已存在，那么更新相应的定时设置
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(bladeJob.getCronExpression());

                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).usingJobData("data", bladeJob.getMethodParameters())
                        .withSchedule(scheduleBuilder).build();

                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
                return true;
            }
        } catch (SchedulerException e) {
//          发送告警邮件
            asyncService.sendAdminMail(bladeJob.getJobName(), "任务添加失败，请管理员检查");
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除任务
     *
     * @param bladeJob
     * @throws SchedulerException
     */
    public static boolean delJob(BladeJob bladeJob) {
        if (bladeJob == null) {
            return false;
        }
        try {
            schedulerFactoryBean.getScheduler().deleteJob(JobKey.jobKey(bladeJob.getJobName(), bladeJob.getJobGroupName()));
            bladeJob.setStatus(0);
            jobService.updateById(bladeJob);
            return true;
        } catch (SchedulerException e) {
//          删除任务失败，发送告警邮件
            asyncService.sendAdminMail(bladeJob.getJobName(), "任务删除失败，请管理员检查");
            e.printStackTrace();
        }
        return false;
    }


    public void test(Object data) {
        System.out.println(data.toString());
        System.out.println("test任务执行成功");
    }
}
